<template>
  <TresGroup
    :rotation="[-Math.PI * 0.5, 0, Math.PI * 0.09]"
    :position-y="baseHeight + 0.01"
    :scale="[1, 1, midHeightScale]"
  >
    <TresMesh :geometry="mergedGeometry">
      <!-- 使用 MeshPhysicalMaterial 替代 -->
      <TresMeshPhysicalMaterial
        v-bind="materialConfig"
        :envMap="backgroundTexture"
      />
    </TresMesh>
  </TresGroup>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import * as BufferGeometryUtils from "three/addons/utils/BufferGeometryUtils.js";

const props = defineProps({
  baseHeight: {
    type: Number,
    required: true,
  },
  midHeightScale: {
    type: Number,
    required: true,
  },
  blocks: {
    type: Array,
    required: true,
  },
});

// 使用 ref 存储背景纹理
const backgroundTexture = ref(null);

// 在组件挂载后加载 HDR 纹理
onMounted(async () => {
  try {
    // 动态导入 RGBELoader
    const { RGBELoader } = await import("three-stdlib");

    // 创建加载器实例
    const loader = new RGBELoader();

    // 加载 HDR 纹理
    const texture = await new Promise((resolve, reject) => {
      loader.load(
        "./model_assets/umhlanga_sunrise_1k.hdr",
        resolve,
        undefined,
        reject
      );
    });

    // 配置纹理
    texture.mapping = texture.EquirectangularReflectionMapping;
    texture.encoding = texture.sRGBEncoding;

    // 赋值给 ref
    backgroundTexture.value = texture;
  } catch (error) {
    console.error("HDR 纹理加载失败:", error);
  }
});

// 适配 MeshPhysicalMaterial 的材质配置
const materialConfig = {
  transparent: true, // 启用透明
  transmission: 1, // 透明度（0-1）
  thickness: 0.3, // 厚度
  roughness: 0.6, // 粗糙度
  metalness: 0, // 金属度
  ior: 1.5, // 折射率（默认 1.5）
  clearcoat: 1, // 清漆效果
  clearcoatRoughness: 0.1, // 清漆粗糙度
  envMapIntensity: 1, // 环境映射强度
  color: "#d2ebff", // 基础颜色
};

// 合并几何体（保持不变）
const mergedGeometry = computed(() => {
  if (!props.blocks || props.blocks.length === 0) return null;

  const validGeometries = props.blocks
    .filter(
      (item) => item.children && item.children[0] && item.children[0].geometry
    )
    .map((item) => item.children[0].geometry);

  if (validGeometries.length === 0) return null;

  return BufferGeometryUtils.mergeGeometries(validGeometries);
});
</script>
